package se.teamscape.client.view;

import java.util.ArrayList;

import se.teamscape.client.controller.AppController;
import se.teamscape.client.presenter.ShowDataPresenter;
import se.teamscape.client.utils.NameValuePair;

import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;

/**
 * A generic view that presents name/value paired data in a table.
 * If presenter requests edit/delete functionality, buttons will be
 * created on demand.
 * 
 * @author Andreas Borglin
 * 
 */
public class ShowDataView extends BaseView implements ShowDataPresenter.Display {

    private FlexTable mDataTable;
    private FlowPanel mPanel;

    // We create these buttons on demand from the presenter
    // If the presenter doesn't want edit/delete functionality
    // and never calls the get-methods, they are not created.
    private Button mEditButton;
    private Button mDeleteButton;

    public ShowDataView() {
    }

    @Override
    public void init() {

        mDataTable = new FlexTable();
        mPanel = new FlowPanel();

        mPanel.add(mDataTable);

        initWidget(mPanel);

    }

    @Override
    public void setData(ArrayList<NameValuePair<String>> data) {

        int row = 0, col = 0;
        for (NameValuePair<String> pair : data) {
            mDataTable.setText(row, col++, pair.getName());
            mDataTable.setText(row++, col--, pair.getValue());
        }

    }

    @Override
    public HasClickHandlers getDelete() {

        if (mDeleteButton == null) {
            mDeleteButton = new Button();
            mDeleteButton.setText(AppController.getConstants().delete());
            mDeleteButton.setStyleName("HorizontalFlow");
            mPanel.add(mDeleteButton);
        }

        return mDeleteButton;
    }

    @Override
    public HasClickHandlers getEdit() {

        if (mEditButton == null) {
            mEditButton = new Button();
            mEditButton.setText(AppController.getConstants().edit());
            mEditButton.setStyleName("HorizontalFlow");
            mPanel.add(mEditButton);
        }

        return mEditButton;
    }

}
